import { Sequelize } from 'sequelize-typescript';
import { AccessoryEntity } from 'src/logical/accessory/entity/accessory.entity';
import { RpAccount } from 'src/logical/account/entity/account.entity';
import { LoginLogEntity } from 'src/logical/login-log/entity/loginLog.entity';
import { MenuEntity } from 'src/logical/menu/entity/menu.entity';
import { RpOrgEntity } from 'src/logical/org/entity/org.entity';
import {
  RoleAccountEntity,
  RoleEntity,
  RoleMenuEntity,
} from 'src/logical/role/entity/role.entity';
import { SysCodeEntity } from 'src/logical/syscode/entity/syscode.entity';

import db from '../../config/db';

export const databaseProviders = [
  {
    provide: 'SequelizeToken',
    useFactory: async () => {
      const sequelize = new Sequelize(
        db.mysql.database,
        db.mysql.user,
        db.mysql.password || null,
        {
          // 自定义主机; 默认值: localhost
          host: db.mysql.host, // 数据库地址
          // 自定义端口; 默认值: 3306
          port: db.mysql.port,
          dialect: 'mysql',
          logging: true,
          pool: {
            max: db.mysql.connectionLimit, // 连接池中最大连接数量
            min: 0, // 连接池中最小连接数量
            acquire: 30000,
            idle: 10000, // 如果一个线程 10 秒钟内没有被使用过的话，那么就释放线程
          },
          timezone: '+08:00', // 东八时区
          dialectOptions: {
            // dataString: true,
            typeCast: true,
            // useUTC: false,
          },
        },
      );
      sequelize.addModels([
        RpAccount,
        AccessoryEntity,
        LoginLogEntity,
        RoleEntity,
        MenuEntity,
        RoleAccountEntity,
        RoleMenuEntity,
        RpOrgEntity,
        SysCodeEntity
      ]);
      await sequelize.sync({ alter: true });
      return sequelize;
    },
  },
];
